<?php
class BungaPohon{
	public $tgl_pengecekan;
	public $no_individu;
	public $jml_jantan;
	public $jml_betina;
	public $jml_kastrasi;
	public $jml_dibuang;
	public $bagging;
}

class PembuanganBungaModel{
	private $db;
	private $subbagian;
	
	private $validColumn;

	private $data;
	
	function PembuanganBungaModel($dbObject){
		$this->subbagian 	= 'pembuangan_bunga';		
		$this->db 			= $dbObject;

		$this->validColumn  = array(
			'no_individu', 
			'jml_bunga_jantan', 
			'jml_bunga_kastrasi');
	}
	
	function format($data){
		$result = array();
		foreach($this->validColumn as $v){
			if( isset($data[$v]) )
				$result[$v] = $data[$v];
			else
				$result[$v] = NULL;
		}
		
		return $result;
	}
	
	private function updateBungaPohon($result){
		$bungaLama = new BungaPohon();
		$bungaLama->tgl_pengecekan 	= $result[0]['tgl_pengecekan'];
		$bungaLama->no_individu 	= $result[0]['no_individu'];
		$bungaLama->jml_jantan 		= $result[0]['jml_jantan'];
		$bungaLama->jml_betina 		= $result[0]['jml_betina'];
		$bungaLama->jml_dibuang 	= $result[0]['jml_dibuang'];
		$bungaLama->jml_kastrasi 	= $result[0]['jml_kastrasi'];
		
		$bungaBaru = new BungaPohon();
		$bungaBaru->tgl_pengecekan 	= $bungaLama->tgl_pengecekan;
		$bungaBaru->no_individu 	= $bungaLama->no_individu;
		$bungaBaru->jml_jantan 		= $bungaLama->jml_jantan - $this->data['jml_bunga_jantan'];
		$bungaBaru->jml_dibuang 	= $bungaLama->jml_dibuang + $this->data['jml_bunga_jantan'];
		$bungaBaru->jml_kastrasi 	= $bungaLama->jml_kastrasi + $this->data['jml_bunga_kastrasi'];
		
		$query  = 'UPDATE `panen`.`bunga_pohon` SET `jml_jantan` = "'.$bungaBaru->jml_jantan.'", `jml_dibuang`="'.$bungaBaru->jml_dibuang.'", `jml_kastrasi`="'.$bungaBaru->jml_kastrasi.'" WHERE `no_individu` = "'.$this->data['no_individu'].'" AND `tgl_pengecekan` = "'.$bungaBaru->tgl_pengecekan.'"';
		$this->db->query($query);
	}
	
	private function getOldData(){		
		//lihat jumlah lama
		$query  = 'SELECT * FROM `panen`.`bunga_pohon` WHERE `no_individu` = "'.$this->data['no_individu'].'" ORDER BY `tgl_pengecekan` DESC';
		$result = $this->db->get_results($query, ARRAY_A);
		
		return $result; // NULL kalo tidak ditemukan..
	}
	
	function put($data){		
		$this->data	= $this->format($data);// buang field2 yang tidak dibutuhkan
		
		// ambil data lama
		$oldData 	=  $this->getOldData();
		
		if( !$oldData ){
			// data tidak ditemukan
			return UPDATE_FAIL;
		}
		else{
			// do updating
			$this->updateBungaPohon($oldData);
			return UPDATE_OK;
		}
	}	
}
?>